#Proyecto 2 Introduccion a los Sistemas Embebidos
#!/usr/bin/env python
import pygtk
pygtk.require('2.0')
import gtk
import gobject
import pygst
pygst.require('0.10')
gobject.threads_init()
import gst
import time
import random
from Tkinter import * #get cards
def get_cards():
    return [i%8 for i in range(16)]#arreglo de 16, numeros del 0-7
def init_exposed():
    return [False for i in range(16)]

def get_images():
    return[gtk.Image() for i in range(16)]



class DemoApp(object):
    """GStreamer/PocketSphinx Demo Application"""
    def __init__(self):
        """Initialize a DemoApp object"""
        self.init_gui()
        self.init_gst()
        global cards,exposed,positions,moves, card1,card2,state,B1,B2
        cards=get_cards()
        random.shuffle(cards)
        positions=[-1,-1]
        moves=0
        self.card1 = -1
        self.card2 = -1
        self.global_state = 0
        self.images = get_images()

        for i in range(8):
            self.images[i].set_from_file("/home/cy/sphinx/python/images/"+str(i)+".png")

    def init_gui(self):
        """Initialize the GUI components"""
        self.window = gtk.Window()
        self.window.connect("delete-event", gtk.main_quit)
        self.window.set_default_size(600,400)
        self.window.set_title("MEMORY")
        self.window.set_border_width(10)
        vbox = gtk.VBox()
        self.textbuf = gtk.TextBuffer()
        self.text = gtk.TextView(self.textbuf)
        self.text.set_wrap_mode(gtk.WRAP_WORD)
        vbox.pack_start(self.text)
        self.speak_button = gtk.ToggleButton("Hablar")
        self.speak_button.connect('clicked', self.speak_clicked)

        self.accept_button = gtk.ToggleButton("Aceptar")
        self.accept_button.connect('clicked', self.accept_clicked)
        self.cancel_button = gtk.ToggleButton("Borrar")
        self.cancel_button.connect('clicked', self.cancel_clicked)

        vbox.pack_start(self.speak_button, False, False, 5)
        vbox.pack_start(self.accept_button, False, False, 6)
        vbox.pack_start(self.cancel_button, False, False, 7)
        self.window.add(vbox)
        self.window.show_all()

    def init_gst(self):
        """Initialize the speech components"""
        self.pipeline = gst.parse_launch('gconfaudiosrc ! audioconvert ! audioresample '
                                         + '! vader name=vad auto-threshold=true '
                                         + '! pocketsphinx name=asr ! fakesink')
        asr = self.pipeline.get_by_name('asr')
        asr.connect('partial_result', self.asr_partial_result)
        asr.connect('result', self.asr_result)
        asr.set_property('configured', True)
        asr.set_property('lm', '/home/cy/sphinx/python/LanguageModel/instrucciones.lm')
        asr.set_property('dict', '/home/cy/sphinx/python/LanguageModel/instrucciones.dic')

        bus = self.pipeline.get_bus()
        bus.add_signal_watch()
        bus.connect('message::application', self.application_message)

        self.pipeline.set_state(gst.STATE_PAUSED)

    def asr_partial_result(self, asr, text, uttid):
        """Forward partial result signals on the bus to the main thread."""
        struct = gst.Structure('partial_result')
        struct.set_value('hyp', text)
        struct.set_value('uttid', uttid)
        asr.post_message(gst.message_new_application(asr, struct))

    def asr_result(self, asr, text, uttid):
        """Forward result signals on the bus to the main thread."""
        struct = gst.Structure('result')
        struct.set_value('hyp', text)
        struct.set_value('uttid', uttid)
        asr.post_message(gst.message_new_application(asr, struct))

    def application_message(self, bus, msg):
        """Receive application messages from the bus."""
        msgtype = msg.structure.get_name()
        if msgtype == 'partial_result':
            self.partial_result(msg.structure['hyp'], msg.structure['uttid'])
        elif msgtype == 'result':
            self.final_result(msg.structure['hyp'], msg.structure['uttid'])
            self.pipeline.set_state(gst.STATE_PAUSED)
            self.speak_button.set_active(False)

    def partial_result(self, hyp, uttid):
        """Delete any previous selection, insert text and select it."""
        # All this stuff appears as one single action
        self.textbuf.begin_user_action()
        self.textbuf.delete_selection(True, self.text.get_editable())
        self.textbuf.insert_at_cursor(hyp)
        ins = self.textbuf.get_insert()
        iter = self.textbuf.get_iter_at_mark(ins)
        iter.backward_chars(len(hyp))
        self.textbuf.move_mark(ins, iter)
        self.textbuf.end_user_action()

    def final_result(self, hyp, uttid):
        """Insert the final result."""
        # All this stuff appears as one single action
        self.textbuf.begin_user_action()
        self.textbuf.delete_selection(True, self.text.get_editable())
        self.textbuf.insert_at_cursor(hyp)
        self.textbuf.end_user_action()

    # Funcion del boton speak 
    def speak_clicked(self, speak_button):
        """Handle button presses."""
        if speak_button.get_active():
            speak_button.set_label("Parar")
            self.pipeline.set_state(gst.STATE_PLAYING)
        else:
            speak_button.set_label("Hablar")
            vader = self.pipeline.get_by_name('vad')
            vader.set_property('silent', True)
    
    # Funcion del boton Aceptar 
    def accept_clicked(self, accept_button):
        """Handle button presses."""
        if accept_button.get_active():
                                  
            self.gamewindow = gtk.Window()
            self.gamewindow.connect("delete-event", gtk.main_quit)
            self.gamewindow.set_default_size(400,400)
            self.gamewindow.set_title("MEMORIA")
            self.gamewindow.set_border_width(10)
            #gamevbox = gtk.VBox()
            #pack_start(self.text
            #self.text.set_parent_window(self.gamewindow
            #self.text.unparent()
            #self.text.set_parent(self.gamewindow)
            #self.gamewindow.add(self.text)
            grid = gtk.Table(5, 5, gtk.TRUE)
            self.gamewindow.add(grid)

            self.button1 = gtk.ToggleButton(label="?")
            self.button1.connect('clicked', self.button1_clicked)
            self.button2 = gtk.ToggleButton(label="?")
            self.button2.connect('clicked', self.button2_clicked)
            self.button3 = gtk.ToggleButton(label="?")
            self.button3.connect('clicked', self.button3_clicked)
            self.button4 = gtk.ToggleButton(label="?")
            self.button4.connect('clicked', self.button4_clicked)
            self.button5 = gtk.ToggleButton(label="?")
            self.button5.connect('clicked', self.button5_clicked)
            self.button6 = gtk.ToggleButton(label="?")
            self.button6.connect('clicked', self.button6_clicked)
            self.button7 = gtk.ToggleButton(label="?")
            self.button7.connect('clicked', self.button7_clicked)
            self.button8 = gtk.ToggleButton(label="?")
            self.button8.connect('clicked', self.button8_clicked)
            self.button9 = gtk.ToggleButton(label="?")
            self.button9.connect('clicked', self.button9_clicked)
            self.button10 = gtk.ToggleButton(label="?")
            self.button10.connect('clicked', self.button10_clicked)
            self.button11 = gtk.ToggleButton(label="?")
            self.button11.connect('clicked', self.button11_clicked)
            self.button12 = gtk.ToggleButton(label="?")
            self.button12.connect('clicked', self.button12_clicked)
            self.button13 = gtk.ToggleButton(label="?")
            self.button13.connect('clicked', self.button13_clicked)
            self.button14 = gtk.ToggleButton(label="?")
            self.button14.connect('clicked', self.button14_clicked)
            self.button15 = gtk.ToggleButton(label="?")
            self.button15.connect('clicked', self.button15_clicked)
            self.button16 = gtk.ToggleButton(label="?")
            self.button16.connect('clicked', self.button16_clicked)
            

            
            
            self.buttona = gtk.ToggleButton()
            self.buttonb = gtk.ToggleButton()
            self.buttonc = gtk.ToggleButton()
            self.buttond = gtk.ToggleButton()
            self.buttone = gtk.ToggleButton()
            self.buttonf = gtk.ToggleButton()
            self.buttong = gtk.ToggleButton()
            self.buttonh = gtk.ToggleButton()
            self.buttoni = gtk.ToggleButton()
            
            self.imagea = gtk.Image()
            self.imagea.set_from_file("/home/cy/sphinx/python/images/aegis.jpg")
            self.buttona.set_image(self.imagea)
            self.imageb = gtk.Image()
            self.imageb.set_from_file("/home/cy/sphinx/python/images/aegis.jpg")
            self.buttonb.set_image(self.imageb)
            self.imagec = gtk.Image()
            self.imagec.set_from_file("/home/cy/sphinx/python/images/aegis.jpg")
            self.buttonc.set_image(self.imagec)
            self.imaged = gtk.Image()
            self.imaged.set_from_file("/home/cy/sphinx/python/images/aegis.jpg")
            self.buttond.set_image(self.imaged)
            self.imagee = gtk.Image()
            self.imagee.set_from_file("/home/cy/sphinx/python/images/aegis.jpg")
            self.buttone.set_image(self.imagee)
            self.imagef = gtk.Image()
            self.imagef.set_from_file("/home/cy/sphinx/python/images/aegis.jpg")
            self.buttonf.set_image(self.imagef)
            self.imageg = gtk.Image()
            self.imageg.set_from_file("/home/cy/sphinx/python/images/aegis.jpg")
            self.buttong.set_image(self.imageg)
            self.imageh = gtk.Image()
            self.imageh.set_from_file("/home/cy/sphinx/python/images/aegis.jpg")
            self.buttonh.set_image(self.imageh)
            self.imagei = gtk.Image()
            self.imagei.set_from_file("/home/cy/sphinx/python/images/aegis.jpg")
            self.buttoni.set_image(self.imagei)
            
            

            grid.attach(self.button1, 0, 1, 0, 1)
            grid.attach(self.button2, 1, 2, 0, 1)
            grid.attach(self.button3, 0, 1, 1, 2)
            grid.attach(self.button4, 1, 2, 1, 2)
            grid.attach(self.button5, 0, 1, 2, 3)
            grid.attach(self.button6, 1, 2, 2, 3)
            grid.attach(self.button7, 0, 1, 3, 4)
            grid.attach(self.button8, 1, 2, 3, 4)
            grid.attach(self.button9, 2, 3, 0, 1)
            grid.attach(self.button10, 3, 4, 0, 1)
            grid.attach(self.button11, 2, 3, 1, 2)
            grid.attach(self.button12, 3, 4, 1, 2)
            grid.attach(self.button13, 2, 3, 2, 3)
            grid.attach(self.button14, 3, 4, 2, 3)
            grid.attach(self.button15, 2, 3, 3, 4)
            grid.attach(self.button16, 3, 4, 3, 4)
            grid.attach(self.buttona, 4, 5, 0, 1)
            grid.attach(self.buttonb, 4, 5, 1, 2)
            grid.attach(self.buttonc, 4, 5, 2, 3)
            grid.attach(self.buttond, 4, 5, 3, 4)
            grid.attach(self.buttone, 4, 5, 4, 5)
            grid.attach(self.buttonf, 0, 1, 4, 5)
            grid.attach(self.buttong, 1, 2, 4, 5)
            grid.attach(self.buttonh, 2, 3, 4, 5)
            grid.attach(self.buttoni, 3, 4, 4, 5)
            
            self.gamewindow.show_all()
            #self.window.set_visible(False)
    
    
    def set_state(self,button,card):
        if self.global_state == 1:
            if button != self.B1:
                self.global_state = 0
                self.B2 = button
                self.card2 = card
                if self.check_pair():
                    self.B1.hide()
                    self.B2.hide()
                elif self.check_pair() == False:
                    self.B1.set_active(False)
                    self.B2.set_active(False)
                    self.card2 = -1
                    self.card2 = -1
            else:
                self.global_state = 1

            
            
            
        elif self.global_state == 0:
            self.B1 = button
            self.card1 = card
            #print self.card1
            self.global_state = self.global_state + 1
   

    def check_pair(self):
        if self.card1 == self.card2:
            return True
        else:
            return False

    
    def button1_clicked(self, button1):
        if button1.get_active():
            #button1.set_label(str(cards[0]))
            button1.set_image(self.images[cards[0]])
            self.set_state(self.button1,cards[0])
        else:
            button1.set_label("?")
        
    def button2_clicked(self, button2):
        if button2.get_active():
            button2.set_label(str(cards[1]))
            self.set_state(self.button2,cards[1])

        else:
            button2.set_label("?")
        
    def button3_clicked(self, button3):
        if button3.get_active():
            button3.set_label(str(cards[2]))
            self.set_state(self.button3,cards[2])
        else:
            button3.set_label("?")
                
    def button4_clicked(self, button4):
        if button4.get_active():
            button4.set_label(str(cards[3]))
            self.set_state(self.button4,cards[3])
        else:
            button4.set_label("?")
            
    def button5_clicked(self, button5):
        if button5.get_active():
            button5.set_label(str(cards[4]))
            self.set_state(button5,cards[4])
        else:
            button5.set_label("?")
            
    def button6_clicked(self, button6):
        if button6.get_active():
            button6.set_label(str(cards[5]))
            self.set_state(button6,cards[5])
        else:
            button6.set_label("?")
            
    def button7_clicked(self, button7):
        if button7.get_active():
            button7.set_label(str(cards[6]))
            self.set_state(button7,cards[6])
        else:
            button7.set_label("?")
            
    def button8_clicked(self, button8):
        if button8.get_active():
            button8.set_label(str(cards[7]))
            self.set_state(button8,cards[7])
        else:
            button8.set_label("?")
            
    def button9_clicked(self, button9):
        if button9.get_active():
            button9.set_label(str(cards[8]))
            self.set_state(button9,cards[8])
        else:
            button9.set_label("?")
            
    def button10_clicked(self, button10):
        if button10.get_active():
            button10.set_label(str(cards[9]))
            self.set_state(button10,cards[9])
        else:
            button10.set_label("?")
            
    def button11_clicked(self, button11):
        if button11.get_active():
            button11.set_label(str(cards[10]))
            self.set_state(button11,cards[10])
        else:
            button11.set_label("?")
            
    def button12_clicked(self, button12):
        if button12.get_active():
            button12.set_label(str(cards[11]))
            self.set_state(button12,cards[11])
        else:
            button12.set_label("?")
            
    def button13_clicked(self, button13):
        if button13.get_active():
            button13.set_label(str(cards[12]))
            self.set_state(button13,cards[12])
        else:
            button13.set_label("?")
            
    def button14_clicked(self, button14):
        if button14.get_active():
            button14.set_label(str(cards[13]))
            self.set_state(button14,cards[13])
        else:
            button14.set_label("?")
            
    def button15_clicked(self, button15):
        if button15.get_active():
            button15.set_label(str(cards[14]))
            self.set_state(button15,cards[14])
        else:
            button15.set_label("?")
            
    def button16_clicked(self, button16):
        if button16.get_active():
            button16.set_label(str(cards[15]))
            self.set_state(button16,cards[15])
        else:
            button16.set_label("?")
            
    # Funcion del boton Cancelar 
    def cancel_clicked(self, cancel_button):
        """Handle button presses."""
        if cancel_button.get_active():
            self.textbuf.set_text("")



app = DemoApp()
gtk.main()
